window.onload = function() {
    if(Kernal.isLogin()) {
        initUserInfo();
    }

    // 设置监听器，点击搜索按钮后，执行对应函数
    document.getElementById('search-btn').addEventListener('click', function() {
        search();
    });

    // TODO: 在此为 top-right 元素设置监听器
    // document.getElementById('top-right') ...
    document.getElementById('top-right').addEventListener('click', function() {
        clickLogin();
    });

    //监听键盘回车事件
    $('#search-input').bind('keyup', function(e){
        if (e.key == 'Enter'){
            search();
        }
    })

    //悬停变色
    var value = document.getElementById('top-left').getElementsByTagName('a');
    let len = value.length;
    for (let i = 0; i < len; i++){
        if(value[i].href.match(/https/) == null){
            value[i].className = 'red';
        }
    }
}

function search() {
    // TODO: 搜索触发后的行为
    console.log('');
    var value = document.getElementsByTagName('input')[0].value;
    if (value == '') {
        alert('请输入搜索内容');
    }
    else{
        var regu = "^[ ]+$";
        var re = new RegExp(regu);
        if (re.test(value)) {
            alert('请输入搜索内容');
        }
        else {
            // alert(value);
            // location.href = 'https://baidu.com/s?wd=' + value; //此窗口打开
            window.open('https://baidu.com/s?wd=' + value); //打开新窗口
        }
    }
}

function clickLogin() {
    if(!Kernal.isLogin()) {
        login();
    }
    else {
        logout();
    }
}

function initUserInfo() {
    // TODO: 修改页面显示错误的 bug
    let username = Kernal.getUserName();
    // let content = `<div id="user">
    //                     <span id="user-img">
    //                         <img src="img/user.jpg" />
    //                     </span>
    //                     <span id="name"> ${username} </span>
    //                 </div>`;

    //<xmp style="font-size: 9px; line-height: 12px; overflow: hidden; text-overflow: ellipsis;">${username}</xmp> //旁门左道
    let content = `<div id="user">
                        <span id="user-img">
                            <img src="img/user.jpg" />
                        </span>
                        <span id="name"></span>
                    </div>`;
    document.getElementById('top-right').innerHTML = content;
    document.getElementById('name').textContent = username;
}

// ============================================================ 你不需要去关注的代码

function login() {
    Kernal.login();
    location.reload();
}

function logout() {
    Kernal.logout();
    location.reload();
}